/**     
* @Title: TestController.java   
* @Package me.springboot.session.web   
* @Description: TODO   
* @author xaoyaoyao
* @date 2017年9月3日 上午11:06:12
*/
package me.springboot.session.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import me.springboot.session.model.User;
import me.springboot.session.service.UserService;

/**
 * @ClassName: TestController
 * @Description: TODO
 * @author xaoyaoyao
 * @date 2017年9月3日 上午11:06:12
 * 
 */
@RestController
public class TestController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public Map<String, Object> firstResp(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		request.getSession().setAttribute("request Url", request.getRequestURL());
		map.put("request Url", request.getRequestURL());
		return map;
	}

	@RequestMapping(value = "/sessions", method = RequestMethod.GET)
	public Object sessions(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sessionId", request.getSession().getId());
		return map;
	}

	@RequestMapping(value = "/redis", method = RequestMethod.GET)
	public String redisTest() {
		System.out.println("====== 进行 Redis 缓存试验 ======");
		User user = new User();
		String uuid = System.currentTimeMillis() + random() + "";
		user.setUuid(uuid);
		int r = random();
		user.setAge(r);
		user.setName("张三" + r);
		try {
			userService.save(user);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("保存用户出现异常");
		}
		// 第一次查询
		System.out.println(userService.findByUuid(user.getUuid()));
		// 通过缓存查询
		System.out.println(userService.findByUuid(user.getUuid()));
		System.out.println("====== 修改 Redis 缓存数据 ======");
		// 修改用户数据
		user.setAge(r);
		user.setName("李四" + r);
		System.out.println(userService.update(user));
		System.out.println(userService.findByUuid(user.getUuid()));
		return "success";
	}

	private int random() {
		java.util.Random random = new java.util.Random();
		int result = random.nextInt(100);
		return result + 1;
	}
}
